package com.jyy.prefabricated.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.jyy.prefabricated.dto.QuizRecordDto;
import com.jyy.prefabricated.dto.StudentExamDto;
import com.jyy.prefabricated.dto.SubjectiveExcelDto;
import com.jyy.prefabricated.entity.*;
import com.jyy.prefabricated.enums.*;
import com.jyy.prefabricated.exception.CustomException;
import com.jyy.prefabricated.listener.SubjectiveExcelListener;
import com.jyy.prefabricated.mapper.*;
import com.jyy.prefabricated.utils.DateUtils;
import com.jyy.prefabricated.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @version 1.0.0
 * @author: zjj
 */
@Slf4j
@Transactional
@Service
public class StudentExamService {

    @Resource
    private StudentExamMapper studentExamMapper;

    @Resource
    private ExamApplyStudentMapper examApplyStudentMapper;

    @Resource
    private QuestionMapper questionMapper;
    @Resource
    private AreaQuestionMapper areaQuestionMapper;
    @Resource
    private ExamMapper examMapper;

    @Resource
    private ExamPaperMapper examPaperMapper;
    @Resource
    private ExamPaperAreaMapper examPaperAreaMapper;
    @Resource
    private ExamPaperMapper paperMapper;

    @Resource
    private OptionMapper optionMapper;

    @Resource
    private StudentExamQuestionMapper studentExamQuestionMapper;

    @Resource
    private QuestionOptionSortConfigMapper sortConfigMapper;

    @Resource
    private QuestionService questionService;

    @Resource
    private ProjectInfoMapper projectInfoMapper;

    @Resource
    private StudentExamQuestionService studentExamQuestionService;

    @Resource
    private StudentMapper studentMapper;

    @Resource
    private SysTeamMapper teanMapper;
    @Resource
    private CertificateMapper certificateMapper;
    @Resource
    private ExamCertificateMapper examCertificateMapper;

    @Resource
    private StudentCertificateMapper studentCertificateMapper;
    @Resource
    private CourseCategoryExamMapper courseCategoryExamMapper;
    @Resource
    private CourseService courseService;

    @Resource
    private CoursePackageService coursePackageService;

    @Resource
    private CoursePackageMapper coursePackageMapper;
    @Resource
    private QuizRecordMapper quizRecordMapper;

    /**
     * 开始考试
     *
     * @param dto
     * @return
     */
    public Integer insert(StudentExamDto dto) {
        Exam exam = examMapper.selectByPrimaryKey(dto.getExamId());
        if (!ExamStatusEnum.DOING.getValue().equals(exam.getExamStatus())) {
            long startTime = DateUtils.parseDate(exam.getExamStartTime()).getTime();
            long nowTime = new Date().getTime();
            if (nowTime < startTime) {
                throw new CustomException("当前考试还未开始！");
            }
        }
        if (ExamStatusEnum.AFTER.getValue().equals(exam.getExamStatus())) {
            throw new CustomException("当前考试已结束！");
        }
        StudentExam studentExam = new StudentExam();
        studentExam.setExamId(dto.getExamId());
        studentExam.setStudentId(dto.getStudentId());
        studentExam.setStatus(ExamStatusEnum.DOING.getValue());
        //获取当前次数
        int count = selectExamCountByStudentIdAndExamId(dto.getStudentId(), dto.getExamId());
        count = count + 1;

        if (count > exam.getExamCount()) {
            throw new CustomException("已超过允许考试最大次数");
        }
        studentExam.setCurrentCount(count);
        studentExamMapper.insert(studentExam);
        Integer studentExamId = studentExam.getId();
        //初始化试题
        initExamPaperDetail(dto.getExamId(), Arrays.asList(studentExamId));
        return studentExamId;
    }

    /**
     * 提前准备生成学员试卷考题
     *
     * @param minutes
     */
    public void initPaperEarly(int minutes) {

        Calendar beforeTime = Calendar.getInstance();
        beforeTime.add(Calendar.MINUTE, minutes);// minutes分钟之后的时间
        Date beforeDate = beforeTime.getTime();
        //查询待开始的考试
        List<Exam> exams = examMapper.selectWaitStartExam(beforeDate);
        List<Integer> ids = exams.stream().filter(e -> e.getExamCount() > 0).map(e -> e.getId()).collect(Collectors.toList());
        log.info("共有{}场考试需要生成试卷,", ids.size());
        if (ids.size() > 0) {
            //获取参与这些考试的学员
            List<ExamStudentVo> students = examApplyStudentMapper.selectByExamIds(ids);
            for (Integer examId : ids) {
                List<Integer> studentExamIds = new ArrayList<>();
                List<Integer> studentIds = students.stream().filter(e -> e.getExamId().equals(examId)).map(ExamStudentVo::getStudentId).collect(Collectors.toList());
                if (studentIds.size() > 0) {
                    log.info("开始生成examId:{}考试的试卷信息,参加考试的人数为:{}", examId, studentIds.size());
                    List<StudentExam> existStudentExam = studentExamMapper.selectByExamId(examId);
                    for (Integer studentId : studentIds) {
                        if (existStudentExam.stream().noneMatch(e -> e.getStudentId().equals(studentId))) {
                            log.info("开始生成examId:{}考试的试卷信息,参加考试的人数为:{}", examId, studentIds.size());
                            StudentExam studentExam = new StudentExam();
                            studentExam.setExamId(examId);
                            studentExam.setStudentId(studentId);
                            studentExam.setStatus(ExamStatusEnum.BEFORE.getValue());
                            studentExam.setCurrentCount(1);
                            studentExamMapper.insert(studentExam);
                            studentExamIds.add(studentExam.getId());
                        }

                    }
                    initExamPaperDetail(examId, studentExamIds);
                }
            }
        }
    }

    /**
     * 初始化考试试题
     *
     * @param examId
     */
    public void initExamPaperDetail(Integer examId, List<Integer> studentExamIds) {
        List<StudentExamQuestion> examQuestions = new ArrayList<>();
        Exam exam = examMapper.selectByPrimaryKey(examId);
        ExamPaper paper = examPaperMapper.selectByPrimaryKey(exam.getPaperId());
        List<ExamPaperArea> areas = paper.getAreas();
        boolean sfxt = false;
        List<ExamPaperAreaRule> rules = new ArrayList<>();
        for (ExamPaperArea area : areas) {
            if (area.getExtractingStatus().equals(ExtractingStatusEnum.AUTONOMY.getValue())) {
                sfxt = true;
            } else {
                rules.addAll(area.getRules());
            }

        }
        if (sfxt == false && rules.size() == 0) {
            throw new CustomException("当前试卷规则未配置！");
        }
        List<Question> questions = new ArrayList<>();
        if (rules!=null && rules.size()>0) {
            List<Integer> questionBankIds = rules.stream().map(e -> e.getQuestionBankId()).collect(Collectors.toList());
            //根据配置的题库id题目

            questions = questionMapper.selectByQuestionBankIds(questionBankIds);
        }
        /*List<Integer> questionBankIds = rules.stream().map(e -> e.getQuestionBankId()).collect(Collectors.toList());
        //根据配置的题库id题目

        List<Question> questions = questionMapper.selectByQuestionBankIds(questionBankIds);*/

        for (Integer studentExamId : studentExamIds) {
            List<Question> temp = new ArrayList<>();
            temp.addAll(questions);
            examQuestions = fetchQuestionByConfig(rules, temp, exam.getIfRandom(), studentExamId, areas);
            studentExamQuestionMapper.batchInsert(examQuestions);
        }
    }

    /**
     * 结束考试
     *
     * @param studentExamId
     */
    public ExamResultVo finishExam(Integer studentExamId) {
        ExamResultVo resultVo = new ExamResultVo();
        Double score = 0D;
        Integer rightCount = 0;
        Integer errorCount = 0;
        Integer unAnswerCount = 0;
        Integer answerCount = 0;
        StudentExam studentExam = studentExamMapper.selectByPrimaryKey(studentExamId);
        Exam exam = examMapper.selectByPrimaryKey(studentExam.getExamId());
        List<StudentExamQuestion> questions = studentExamQuestionMapper.selectByStudentExamId(studentExamId);
        if (ExamStatusEnum.AFTER.getValue().equals(studentExam.getStatus())) {

            //当前考试已经交卷了
            for (StudentExamQuestion question : questions) {
                Question result = questionService.selectById(question.getQuestionId());
                if (result.getQuestionType().equals(QuestionTypeEnum.SINGLE.getValue())
                        || result.getQuestionType().equals(QuestionTypeEnum.MULTIPLE.getValue())
                        || result.getQuestionType().equals(QuestionTypeEnum.JUDGE.getValue())
                        || result.getQuestionType().equals(QuestionTypeEnum.GAP.getValue())) {
                    if (question.getIfRight()) {
                        score += question.getScore();
                        rightCount++;
                    } else {
                        errorCount++;
                        if (result.getQuestionType().equals(QuestionTypeEnum.GAP.getValue())) {

                            String[] strs = question.getSubjectiveAnswer().split("、");

                            String[] strsB = result.getQuestionAnswer().split("、");
                            int count = 0;
                            for (int i = 0; i < strs.length; i++) {
                                if (strs[i].equals(strsB[i])) {
                                    count++;
                                }
                            }
                            score += question.getScore() * count / (strs.length);
                        }
                    }
                    if (question.getAnswer() == null && question.getSubjectiveAnswer() == null) {
                        unAnswerCount++;
                    } else {
                        answerCount++;
                    }
                }
            }
        } else {
            //当前考试还没交卷需要去计算成绩
            List<Integer> questionIds = questions.stream().map(e -> e.getQuestionId()).collect(Collectors.toList());
            List<Option> options = optionMapper.selectByQuestionIds(questionIds);
            Boolean temp = true;
            for (StudentExamQuestion question : questions) {
                Question result = questionService.selectById(question.getQuestionId());

                if (result.getQuestionType().equals(QuestionTypeEnum.ESSAY.getValue())) {
                    temp = false;
                }

                //问答题判断
                if (result.getQuestionType().equals(QuestionTypeEnum.GAP.getValue())
                        || result.getQuestionType().equals(QuestionTypeEnum.ESSAY.getValue())) {
                    if (result.getQuestionAnswer().equals(question.getSubjectiveAnswer())) {
                        question.setIfRight(true);
                    } else {
                        question.setIfRight(false);
                    }
                }

                //填空题判断
                if (result.getQuestionType().equals(QuestionTypeEnum.GAP.getValue())) {
                    if (result.getQuestionAnswer().equals(question.getSubjectiveAnswer())) {
                        question.setIfRight(true);
                    } else {
                        question.setIfRight(false);

                    }
                }


                //单选、多选
                if (result.getQuestionType().equals(QuestionTypeEnum.SINGLE.getValue())
                        || result.getQuestionType().equals(QuestionTypeEnum.MULTIPLE.getValue())) {
                    //筛选出正确答案的选项数组
                    List<Integer> ids = options.stream().filter(e -> e.getIfAnswer() && e.getQuestionId().equals(question.getQuestionId())).map(e -> e.getId()).collect(Collectors.toList());
                    Boolean ifRight = true;
                    if (question.getAnswer() != null && !"".equals(question.getAnswer()) && !"[]".equals(question.getAnswer())) {
                        List<Integer> submitAnswers = JSON.parseArray(question.getAnswer(), Integer.class);

                        if (ids.size() != submitAnswers.size()) {
                            ifRight = false;
                        } else {
                            for (Integer tt : submitAnswers) {
                                if (!ids.contains(tt)) {
                                    ifRight = false;
                                }

                            }
                        }


                    } else {
                        ifRight = false;
                    }
                    question.setIfRight(ifRight);
                    if (question.getIfRight()) {
                        score += question.getScore();
                        rightCount++;
                    } else {
                        errorCount++;
                    }
                    if (question.getAnswer() == null) {
                        unAnswerCount++;
                    } else {
                        answerCount++;
                    }
                } else if (result.getQuestionType().equals(QuestionTypeEnum.JUDGE.getValue())) {
                    //判题
                    List<Integer> submitAnswers = JSON.parseArray(question.getAnswer(), Integer.class);
                    Boolean ifRight = true;
                    if (question.getAnswer() != null && !"".equals(question.getAnswer()) && !"[]".equals(question.getAnswer())) {
                        Boolean mark = true;
                        //1正确，2错误
                        if (submitAnswers.get(0) == 2) {
                            mark = false;
                        }
                        if (!mark.equals(result.getJudgmentAnswer())) {
                            ifRight = false;
                        }
                    } else {
                        ifRight = false;
                    }
                    question.setIfRight(ifRight);
                    if (question.getIfRight()) {
                        score += question.getScore();
                        rightCount++;
                    } else {
                        errorCount++;
                    }
                    if (question.getAnswer() == null) {
                        unAnswerCount++;
                    } else {
                        answerCount++;
                    }
                }
            }
            studentExamQuestionMapper.updateResultBatch(questions);
            studentExam.setScore(score);
            studentExam.setStatus(ExamStatusEnum.AFTER.getValue());
            if (temp == true) {
                studentExam.setReadOverStatus(ReadOverStatusEnum.YES.getValue());
            }
            studentExamMapper.updateByPrimaryKeySelective(studentExam);
        }
        //删除配置的选项顺序
        sortConfigMapper.deleteByStudentExamId(studentExamId);
        resultVo.setScore(score);
        resultVo.setUnAnswerCount(unAnswerCount);
        resultVo.setAnswerCount(answerCount);
        resultVo.setRightCount(rightCount);
        resultVo.setErrorCount(errorCount);
        resultVo.setLeftCount(exam.getExamCount() - studentExam.getCurrentCount());
        return resultVo;
    }


    /**
     * 根据配置获取学员考试题目
     *
     * @param rules
     * @param questions
     * @param ifRandom
     * @param studentExamId
     * @return
     */
    public List<StudentExamQuestion> fetchQuestionByConfig(List<ExamPaperAreaRule> rules, List<Question> questions, Boolean ifRandom, Integer studentExamId, List<ExamPaperArea> areas) {
        List<StudentExamQuestion> examQuestions = new ArrayList<>();
        for (ExamPaperArea examPaperArea : areas) {
            /**
             * 如果是自主选题
             */
            if (examPaperArea.getExtractingStatus().equals(ExtractingStatusEnum.AUTONOMY.getValue())) {
                AreaQuestion areaQuestion = new AreaQuestion();
                areaQuestion.setAreaId(examPaperArea.getId());
                List<AreaQuestion> areaQuestionList = areaQuestionMapper.queryAll(areaQuestion);
                ExamPaperArea area = examPaperAreaMapper.selectByPrimaryKey(examPaperArea.getId());
                for (AreaQuestion question : areaQuestionList) {
                    StudentExamQuestion examQuestion = new StudentExamQuestion();
                    examQuestion.setQuestionId(question.getQuestionId());
                    examQuestion.setScore(area.getGrade());
                    examQuestion.setAreaId(question.getAreaId());
                    examQuestion.setStudentExamId(studentExamId);
                    examQuestions.add(examQuestion);
                }
            } else {
                for (ExamPaperAreaRule rule : examPaperArea.getRules()) {
                    List<Question> filterQuestions = questions.stream().filter(e -> e.getQuestionBankId().equals(rule.getQuestionBankId())).collect(Collectors.toList());
                    if (rule.getQuestionType() != null) {
                        filterQuestions = filterQuestions.stream().filter(e -> e.getQuestionType().equals(rule.getQuestionType())).collect(Collectors.toList());
                    }
                    if (rule.getStemType() != null) {
                        filterQuestions = filterQuestions.stream().filter(e -> e.getStemType().equals(rule.getStemType())).collect(Collectors.toList());
                    }
                    if (rule.getDifficulty() != null) {
                        filterQuestions = filterQuestions.stream().filter(e -> e.getDifficulty().equals(rule.getDifficulty())).collect(Collectors.toList());
                    }
                    if (rule.getQuestionCount() > filterQuestions.size()) {
                        throw new CustomException("题库题目数量少于配置数量");
                    }
                    List<Question> checkedQuestions = new ArrayList<>();
                    //根据是否随机抽取题目
                    if (examPaperArea.getExtractingStatus().equals(ExtractingStatusEnum.RANDOM.getValue())) {
                        checkedQuestions = getRandomList(filterQuestions, rule.getQuestionCount());
                    } else {
                        checkedQuestions = filterQuestions.subList(0, rule.getQuestionCount());
                    }

                    if (rule.getQuestionType().equals(QuestionTypeEnum.MATERIALS.getValue())) {
                        List<Question> sonList = new ArrayList<>();
                        for (Question qt : checkedQuestions) {
                            List<Question> list = questionMapper.selectByParams(null, null, null, null, null, null, qt.getId(), null, null);
                            for (int i = 0; i < list.size(); i++) {
                                sonList.add(list.get(i));
                            }
                        }

                        //排除已抽取的题目
                        questions.removeAll(checkedQuestions);
                        for (Question question : sonList) {
                            StudentExamQuestion examQuestion = new StudentExamQuestion();
                            examQuestion.setQuestionId(question.getId());
                            examQuestion.setScore(rule.getGrade());
                            examQuestion.setAreaId(rule.getAreaId());
                            examQuestion.setScore(rule.getGrade());
                            examQuestion.setStudentExamId(studentExamId);
                            examQuestion.setMaterialQuestionId(question.getMaterialQuestionId());
                            examQuestions.add(examQuestion);
                        }

                    } else {
                        //排除已抽取的题目
                        questions.removeAll(checkedQuestions);
                        for (Question question : checkedQuestions) {
                            StudentExamQuestion examQuestion = new StudentExamQuestion();
                            examQuestion.setQuestionId(question.getId());
                            examQuestion.setScore(rule.getGrade());
                            examQuestion.setAreaId(rule.getAreaId());
                            examQuestion.setScore(rule.getGrade());
                            examQuestion.setStudentExamId(studentExamId);
                            examQuestion.setMaterialQuestionId(question.getMaterialQuestionId());
                            examQuestions.add(examQuestion);
                        }
                    }
                }
            }

        }
        for (int i = 0; i < examQuestions.size(); i++) {
            examQuestions.get(i).setSort(i + 1);
        }
        return examQuestions;
    }

    /**
     * 获取随机题目列表
     *
     * @param list
     * @param num
     * @return
     */
    public List<Question> getRandomList(List<Question> list, int num) {
        List olist = new ArrayList<>();
        if (list.size() <= num) {
            return list;
        } else {
            Random random = new Random();
            for (int i = 0; i < num; i++) {
                int intRandom = random.nextInt(list.size() - 1);
                olist.add(list.get(intRandom));
                list.remove(list.get(intRandom));
            }
            return olist;
        }
    }

    /**
     * 更新
     *
     * @param studentExam
     * @return
     */
    public int update(StudentExam studentExam) {
        if (studentExam.getId() == null) {
            throw new CustomException("参数id不能为空");
        }
        return studentExamMapper.updateByPrimaryKeySelective(studentExam);
    }

    /**
     * 获取学员参加考试答题次数
     *
     * @param studentId
     * @param examId
     * @return
     */
    public int selectExamCountByStudentIdAndExamId(Integer studentId, Integer examId) {
        return studentExamMapper.selectExamCountByStudentIdAndExamId(studentId, examId);
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    public int delete(Integer id) {
        return studentExamMapper.deleteByPrimaryKey(id);
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    public StudentExam selectById(Integer id) {
        return studentExamMapper.selectByPrimaryKey(id);
    }

    /**
     * 查询学员当前考试信息
     *
     * @param studentId
     * @return
     */
    public List<StudentExamVo> selectCurrentExamByStudentId(Integer studentId) {
        //获取当前时间
        Date now = new Date();
        //获取考试结束时间在当前之后的通过考试申请的考试

//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        String time=sdf.format(now);
        List<StudentExamVo> exams = examMapper.selectCurrentExamByStudentIdAndDate(studentId, now);
        List<StudentExamVo> applyExams = exams.stream().filter(e -> e.getApplyStatus().equals(ApplyStatusEnum.SUCCESS.getValue())).collect(Collectors.toList());

//        if (applyExams != null && applyExams.size() > 0) {
//            for (StudentExamVo studentExamVo : applyExams) {
//                if (studentExamVo.getAnswerTime() == null) {
//
//                    SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                    try {
//                        Date endDate = ft.parse(studentExamVo.getEndDate());
//                        Date startDate = ft.parse(studentExamVo.getStartDate());
//                        Long answerTime = (endDate.getTime() - startDate.getTime()) / 60000; //分钟
//                        studentExamVo.setAnswerTime(answerTime.intValue());
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                }
//            }
//        }

        return applyExams;
    }

    /**
     * 查询考试成绩
     *
     * @param studentName            学员姓名
     * @param idCard                 身份证
     * @param pointId                考核点
     * @param examApplyId            考试申请
     * @param trainingOrganizationId 机构id
     * @param studentId              学员id
     * @param examId                 考试id
     * @return
     */
    public List<StudentExamScoreVo> selectScoreByParams(String studentName, String idCard, Integer pointId, Integer examApplyId, Integer trainingOrganizationId, Integer studentId, Integer examId, Integer readOverStatus) {
        return studentExamMapper.selectScoreByParams(studentName, idCard, pointId, examApplyId, trainingOrganizationId, studentId, ExamStatusEnum.AFTER.getValue(), examId, readOverStatus);
    }

    /**
     * 查询当前未交卷的学生考试
     *
     * @return
     */
    public List<StudentExamPaperVo> selectByUnEnd() {
        return studentExamMapper.selectByUnEnd();
    }

    /**
     * 查询当前未交卷的学生考试(第一次）
     *
     * @return
     */
    public StudentExamPaperVo selectByUnEndFirst(Integer studentId, Integer examId) {
        return studentExamMapper.selectByUnEndFirst(studentId, examId);
    }

    /**
     * 获取学员考试列表
     *
     * @param studentId 学员id
     * @param examId    考试id
     * @return
     */
    public List<StudentExam> selectByStudentIdAndExamId(Integer studentId, Integer examId) {
        return studentExamMapper.selectByStudentIdAndExamId(studentId, examId);
    }


    /**
     * 批阅试卷详情
     *
     * @param studentExamId
     */
    public ExamResultVo queryDetails(Integer studentExamId) {
        ExamResultVo resultVo = new ExamResultVo();
        Double score = 0D;
        Integer rightCount = 0;
        Integer errorCount = 0;
        Integer unAnswerCount = 0;
        Integer answerCount = 0;
        StudentExam studentExam = studentExamMapper.selectByPrimaryKey(studentExamId);

        score = studentExam.getScore();
        //获取考生姓名、答题时长、交卷时间
        StudentExamVo studentExamVo = studentExamMapper.selectById(studentExamId);
        if (studentExamVo != null) {
            resultVo.setStudentName(studentExamVo.getStudentName());
            resultVo.setUseTime(studentExamVo.getUseTime());
            resultVo.setEndTime(studentExamVo.getEndDate());

        }
        StudentExamPaperVo studentExamPaperVo = studentExamQuestionService.fetchQuestionsByStudentExamId(studentExamId);
        Exam exam = examMapper.selectByPrimaryKey(studentExam.getExamId());
        resultVo.setExamStartTime(exam.getExamStartTime());
        List<SubjectiveAnswerVo> subjectiveList = new ArrayList<>();
        if (studentExamPaperVo.getAreas() != null && studentExamPaperVo.getAreas().size() > 0) {
            for (StudentExamAreaVo studentExamAreaVo : studentExamPaperVo.getAreas()) {
                if (studentExamAreaVo.getQuestions() != null && studentExamAreaVo.getQuestions().size() > 0) {
                    for (StudentExamQuestionVo question : studentExamAreaVo.getQuestions()) {
                        int i = 0;
                        if (question.getQuestionType().equals(QuestionTypeEnum.SINGLE.getValue())
                                || question.getQuestionType().equals(QuestionTypeEnum.MULTIPLE.getValue())
                                || question.getQuestionType().equals(QuestionTypeEnum.JUDGE.getValue())
                                || question.getQuestionType().equals(QuestionTypeEnum.GAP.getValue())) {
                            if (question.getIfRight() != null && question.getIfRight()) {
                                //    score += question.getScore();
                                rightCount++;
                            } else {
                                errorCount++;

//                                if (question.getQuestionType().equals(QuestionTypeEnum.GAP.getValue())) {
//
//                                    Question result = questionService.selectById(question.getQuestionId());
//                                    String[] strs = question.getSubjectiveAnswer().split("、");
//
//                                    String[] strsB = result.getQuestionAnswer().split("、");
//                                    int count = 0;
//                                    for (int j = 0; j < strs.length; j++) {
//                                        if (strs[j].equals(strsB[i])) {
//                                            count++;
//                                        }
//                                    }
//                                    score += question.getScore() * count / (strs.length);
//                                }
                            }

                            if (question.getAnswer() == null && question.getSubjectiveAnswer() == null) {
                                unAnswerCount++;
                            } else {
                                answerCount++;
                            }
                        } else if (question.getQuestionType().equals(QuestionTypeEnum.ESSAY.getValue()) && question.getMaterialQuestionId() == null) {
                            //问答题
                            Question details = questionService.selectById(question.getQuestionId());
                            SubjectiveAnswerVo subjectiveAnswerVo = new SubjectiveAnswerVo();

                            subjectiveAnswerVo.setStudentExamQuestionId(question.getId());
                            //题目id
                            subjectiveAnswerVo.setQuestionId(question.getQuestionId());
                            //题目内容
                            subjectiveAnswerVo.setQuestionContent(details.getName());
                            //参考答案
                            subjectiveAnswerVo.setAnswer(details.getQuestionAnswer());
                            //学生答案
                            subjectiveAnswerVo.setSubjectiveAnswer(question.getSubjectiveAnswer());
                            //批阅得分
                            subjectiveAnswerVo.setSubjectiveScore(question.getSubjectiveScore());
                            subjectiveAnswerVo.setQuestionType(question.getQuestionType());
                            //题目分值
                            subjectiveAnswerVo.setQuestionScore(question.getScore());
                            subjectiveList.add(i++, subjectiveAnswerVo);
                        }
                        //枚举材料题子题
                        else if (question.getQuestionType().equals(QuestionTypeEnum.MATERIALS.getValue())) {
                            List<SubjectiveAnswerVo> subjectiveAnswerVoList = new ArrayList<>();
                            SubjectiveAnswerVo subjectiveAnswerVo = new SubjectiveAnswerVo();
                            for (StudentExamQuestionVo seqv : question.getStudentExamQuestionVo()) {

                                subjectiveAnswerVo.setStudentExamQuestionId(question.getId());
                                //材料题内容
                                subjectiveAnswerVo.setMaterial(question.getTitle());
                                //材料题类型
                                subjectiveAnswerVo.setQuestionType(question.getQuestionType());
                                //题目分值
                                subjectiveAnswerVo.setQuestionScore(question.getScore());

                                //母题学生考试id(构建的)
                                subjectiveAnswerVo.setStudentExamQuestionId(seqv.getId());
                                if (seqv.getQuestionType().equals(QuestionTypeEnum.ESSAY.getValue())) {

                                    SubjectiveAnswerVo sv = new SubjectiveAnswerVo();
                                    //题目id
                                    sv.setQuestionId(seqv.getQuestionId());
                                    //题目内容
                                    sv.setQuestionContent(seqv.getTitle());
                                    //材料题内容
                                    sv.setMaterial(seqv.getMaterial());
                                    //参考答案
                                    sv.setAnswer(seqv.getQuestionAnswer());
                                    //学生答案
                                    sv.setSubjectiveAnswer(seqv.getSubjectiveAnswer());
                                    //批阅得分
                                    sv.setSubjectiveScore(seqv.getSubjectiveScore());
                                    sv.setQuestionType(seqv.getQuestionType());
                                    //题目分值
                                    sv.setQuestionScore(seqv.getScore());
                                    //学生考试题目id
                                    sv.setStudentExamQuestionId(seqv.getId());

                                    subjectiveAnswerVoList.add(sv);
                                }
                                subjectiveAnswerVo.setSubjectiveAnswerVoList(subjectiveAnswerVoList);

                            }
                            subjectiveList.add(i++, subjectiveAnswerVo);
                        }

                    }
                }

            }

        }
//        List<StudentExamQuestion> questions = studentExamQuestionMapper.selectByStudentExamId(studentExamId);
//        for (StudentExamQuestion question : questions) {
//            int i = 0;
//            Question result = questionService.selectById(question.getQuestionId());
//            if (result.getQuestionType().equals(QuestionTypeEnum.SINGLE.getValue())
//                    || result.getQuestionType().equals(QuestionTypeEnum.MULTIPLE.getValue())
//                    || result.getQuestionType().equals(QuestionTypeEnum.JUDGE.getValue())
//                    || result.getQuestionType().equals(QuestionTypeEnum.GAP.getValue())) {
//                if (question.getIfRight()) {
//                    score += question.getScore();
//                    rightCount++;
//                } else {
//                    errorCount++;
//                }
//
//                if (question.getAnswer() == null && question.getSubjectiveAnswer() == null) {
//                    unAnswerCount++;
//                } else {
//                    answerCount++;
//                }
//            } else if (result.getQuestionType().equals(QuestionTypeEnum.ESSAY.getValue()) && question.getMaterialQuestionId() == null) {
//                //问答题
//                Question details = questionService.selectById(question.getQuestionId());
//                SubjectiveAnswerVo subjectiveAnswerVo = new SubjectiveAnswerVo();
//
//                subjectiveAnswerVo.setStudentExamQuestionId(question.getId());
//                //题目id
//                subjectiveAnswerVo.setQuestionId(question.getQuestionId());
//                //题目内容
//                subjectiveAnswerVo.setQuestionContent(details.getName());
//                //参考答案
//                subjectiveAnswerVo.setAnswer(details.getQuestionAnswer());
//                //学生答案
//                subjectiveAnswerVo.setSubjectiveAnswer(question.getSubjectiveAnswer());
//                //批阅得分
//                subjectiveAnswerVo.setSubjectiveScore(question.getSubjectiveScore());
//                subjectiveAnswerVo.setQuestionType(result.getQuestionType());
//                //题目分值
//                subjectiveAnswerVo.setQuestionScore(question.getScore());
//                subjectiveList.add(i++, subjectiveAnswerVo);
//            } else {
//                //材料题
//                Question details = questionService.selectById(question.getQuestionId());
//                SubjectiveAnswerVo subjectiveAnswerVo = new SubjectiveAnswerVo();
//                subjectiveAnswerVo.setStudentExamQuestionId(question.getId());
//                //题目id
//                subjectiveAnswerVo.setQuestionId(question.getQuestionId());
//                //题目内容
//                subjectiveAnswerVo.setQuestionContent(details.getName());
//                //材料题内容
//                subjectiveAnswerVo.setMaterial(details.getMaterial());
//                subjectiveAnswerVo.setQuestionType(result.getQuestionType());
//                //题目分值
//                subjectiveAnswerVo.setQuestionScore(question.getScore());
//
//                //材料题子题
//                if (question.getMaterialQuestionId() == null) {
//
//                    List<StudentExamQuestion> mlist = studentExamQuestionMapper.selectByMaterialQuestionId(question.getQuestionId());
//
//                    List<SubjectiveAnswerVo> subjectiveAnswerVoList = new ArrayList<>();
//                    for (StudentExamQuestion s : mlist) {
//                        Question d = questionService.selectById(s.getQuestionId());
//                        SubjectiveAnswerVo sv = new SubjectiveAnswerVo();
//                        subjectiveAnswerVo.setStudentExamQuestionId(s.getId());
//                        //题目id
//                        sv.setQuestionId(s.getQuestionId());
//                        //题目内容
//                        sv.setQuestionContent(d.getName());
//                        //材料题内容
//                        sv.setMaterial(d.getMaterial());
//                        //参考答案
//                        sv.setAnswer(d.getQuestionAnswer());
//                        //学生答案
//                        sv.setSubjectiveAnswer(s.getSubjectiveAnswer());
//                        //批阅得分
//                        sv.setSubjectiveScore(s.getSubjectiveScore());
//                        sv.setQuestionType(d.getQuestionType());
//                        //题目分值
//                        sv.setQuestionScore(s.getScore());
//
//                        subjectiveAnswerVoList.add(sv);
//
//                    }
//                    subjectiveAnswerVo.setSubjectiveAnswerVoList(subjectiveAnswerVoList);
//
//                    subjectiveList.add(i++, subjectiveAnswerVo);
//                }
//
//            }
//        }
        resultVo.setSubjectiveAnswerVoList(subjectiveList);
        resultVo.setScore(score);
        resultVo.setTotalScore(score + studentExam.getSubjectiveScore());
        resultVo.setUnAnswerCount(unAnswerCount);
        resultVo.setUnAnswerCount(unAnswerCount);
        resultVo.setAnswerCount(answerCount);
        resultVo.setRightCount(rightCount);
        resultVo.setErrorCount(errorCount);
        resultVo.setLeftCount(exam.getExamCount() - studentExam.getCurrentCount());
        Double passGrade = 0d;
        if (exam.getPassGrade() == null) {
            passGrade = 60d;
        } else {
            passGrade = exam.getPassGrade();
        }
        if ((score + studentExam.getSubjectiveScore()) >= passGrade) {
            resultVo.setIsPass(true);
        } else {
            resultVo.setIsPass(false);
        }

        return resultVo;
    }

    /**
     * 批阅试卷
     *
     * @param dto
     */
    public ExamResultVo readOver(StudentExam dto) {
        ExamResultVo resultVo = new ExamResultVo();
        Double score = 0D;
        Integer rightCount = 0;
        Integer errorCount = 0;
        Integer unAnswerCount = 0;
        Integer answerCount = 0;
        StudentExam studentExam = studentExamMapper.selectByPrimaryKey(dto.getId());
        Exam exam = examMapper.selectByPrimaryKey(studentExam.getExamId());
        List<StudentExamQuestion> questions = studentExamQuestionMapper.selectByStudentExamId(dto.getId());
        score = studentExam.getScore();
        //当前考试已经交卷了
        for (StudentExamQuestion question : questions) {
            Question result = questionService.selectById(question.getQuestionId());
            if (result.getQuestionType().equals(QuestionTypeEnum.SINGLE.getValue())
                    || result.getQuestionType().equals(QuestionTypeEnum.MULTIPLE.getValue())
                    || result.getQuestionType().equals(QuestionTypeEnum.JUDGE.getValue())
                    || result.getQuestionType().equals(QuestionTypeEnum.GAP.getValue())) {
                if (question.getIfRight()) {
                    rightCount++;
                } else {
                    errorCount++;

                }

                if (question.getAnswer() == null && question.getSubjectiveAnswer() == null) {
                    unAnswerCount++;
                } else {
                    answerCount++;

                }
            }
        }
        Double subjectiveScore = 0D;
        //统计主观题分数、并修改
        if (dto.getSubjectiveAnswerVoList() != null) {
            for (SubjectiveAnswerVo subjectiveAnswerVo : dto.getSubjectiveAnswerVoList()) {
                //统计材料题子题
                if (subjectiveAnswerVo.getQuestionType().equals(QuestionTypeEnum.MATERIALS.getValue())) {
                    for (SubjectiveAnswerVo su : subjectiveAnswerVo.getSubjectiveAnswerVoList()) {

                        subjectiveScore += su.getSubjectiveScore();
                        StudentExamQuestion studentExamQuestion = new StudentExamQuestion();
                        studentExamQuestion.setId(su.getStudentExamQuestionId());
                        studentExamQuestion.setSubjectiveScore(su.getSubjectiveScore());
                        studentExamQuestionMapper.updateByPrimaryKey(studentExamQuestion);

                    }

                } else {
                    subjectiveScore += subjectiveAnswerVo.getSubjectiveScore();
                    StudentExamQuestion studentExamQuestion = new StudentExamQuestion();
                    studentExamQuestion.setId(subjectiveAnswerVo.getStudentExamQuestionId());
                    studentExamQuestion.setSubjectiveScore(subjectiveAnswerVo.getSubjectiveScore());
                    studentExamQuestionMapper.updateByPrimaryKey(studentExamQuestion);

                }
            }
        }

        resultVo.setScore(score);
        resultVo.setSubjectiveScore(subjectiveScore);
        resultVo.setUnAnswerCount(unAnswerCount);
        resultVo.setAnswerCount(answerCount);
        resultVo.setRightCount(rightCount);
        resultVo.setErrorCount(errorCount);
        resultVo.setLeftCount(exam.getExamCount() - studentExam.getCurrentCount());
        resultVo.setTotalScore(score + subjectiveScore);

        //客观题得分
        studentExam.setScore(score);
        //主观题得分
        studentExam.setSubjectiveScore(subjectiveScore);
        studentExam.setReadOverStatus(ReadOverStatusEnum.YES.getValue());
        //批阅试卷后，update_time不更新，此为交卷时间
        studentExamMapper.updateByPrimaryKeyTime(studentExam);
        return resultVo;
    }


    /**
     * 统计分析
     *
     * @param examId
     */
    public ExamStatisticsVo statistics(Integer examId) {

        ExamStatisticsVo examStatisticsVo = new ExamStatisticsVo();

        Exam exam = examMapper.selectByPrimaryKey(examId);
        if (exam != null) {
            //试卷名称、考试时长、考试次数
            examStatisticsVo.setExamName(exam.getName());
            examStatisticsVo.setAnswerTime(exam.getAnswerTime());
            examStatisticsVo.setExamCount(exam.getExamCount());
            //试卷总分
            Double totalScore = 0d;
            ExamPaper result = paperMapper.selectByPrimaryKey(exam.getPaperId());
            //枚举区域
            if (result.getAreas().size() > 0) {
                for (ExamPaperArea examPaperArea : result.getAreas()) {
                    if (examPaperArea.getExtractingStatus().equals(2)) {
                        AreaQuestion areaQuestion = new AreaQuestion();
                        areaQuestion.setAreaId(examPaperArea.getId());
                        List<AreaQuestion> areaQuestionList = areaQuestionMapper.queryAll(areaQuestion);
                        totalScore += areaQuestionList.size() * examPaperArea.getGrade();
                    } else {
                        if (examPaperArea.getRules().size() > 0) {
                            //枚举规则
                            for (ExamPaperAreaRule examPaperAreaRule : examPaperArea.getRules()) {
                                totalScore += examPaperAreaRule.getQuestionCount() * examPaperAreaRule.getGrade();
                            }
                        }
                    }

                }
            }
            examStatisticsVo.setGrade(totalScore);

        }
        //项目名称
        ProjectInfo projectInfo = projectInfoMapper.selectByPrimaryKey(exam.getProjectId());
        if (projectInfo != null) {
            examStatisticsVo.setProjectName(projectInfo.getName());
        }
        //最高分、最低分、平均分、考试人数
        ExamStatisticsVo esv = studentExamMapper.statistics(examId);
        examStatisticsVo.setMaxGrade(esv.getMaxGrade());
        examStatisticsVo.setMinGrade(esv.getMinGrade());
        examStatisticsVo.setAverageGrade(esv.getAverageGrade());
        examStatisticsVo.setPeopleCount(esv.getPeopleCount());
        //已批阅人数、未批阅人数、提交人数
        ExamStatisticsVo esv2 = studentExamMapper.readOverStatus(examId);
        ExamStatisticsVo esv3 = studentExamMapper.readOverStatusNot(examId);
        if (esv2 != null && esv2.getReadOverCount() != null) {
            examStatisticsVo.setReadOverCount(esv2.getReadOverCount());
        } else {
            examStatisticsVo.setReadOverCount(0);
        }

        if (esv3 != null && esv3.getNotSubmitCount() != null) {
            examStatisticsVo.setNotReadOverCount(esv3.getNotSubmitCount());
        } else {
            examStatisticsVo.setNotReadOverCount(0);
        }

        //提交人数
        examStatisticsVo.setSubmitCount(examStatisticsVo.getNotReadOverCount() + examStatisticsVo.getReadOverCount());
        return examStatisticsVo;
    }


    /**
     * 统计分析  统计图
     *
     * @param examId
     */
    public List<MapVo> statisticsMap(Integer examId, Integer intervalValue) {

        List<MapVo> mapVoList = new ArrayList<>();
        ExamStatisticsVo examStatisticsVo = new ExamStatisticsVo();
        Exam exam = examMapper.selectByPrimaryKey(examId);
        Double totalScore = 0d;
        if (exam != null) {
            //试卷总分
            ExamPaper result = paperMapper.selectByPrimaryKey(exam.getPaperId());
            //枚举区域
            if (result.getAreas().size() > 0) {
                for (ExamPaperArea examPaperArea : result.getAreas()) {
                    if (examPaperArea.getExtractingStatus().equals(2)) {
                        AreaQuestion areaQuestion = new AreaQuestion();
                        areaQuestion.setAreaId(examPaperArea.getId());
                        List<AreaQuestion> areaQuestionList = areaQuestionMapper.queryAll(areaQuestion);
                        totalScore += areaQuestionList.size() * examPaperArea.getGrade();
                    } else {
                        if (examPaperArea.getRules().size() > 0) {
                            //枚举规则
                            for (ExamPaperAreaRule examPaperAreaRule : examPaperArea.getRules()) {
                                totalScore += examPaperAreaRule.getQuestionCount() * examPaperAreaRule.getGrade();
                            }
                        }
                    }

                }
            }
            examStatisticsVo.setGrade(totalScore);

        }

        int count = 0;
        for (Double i = 0d; i < totalScore; i += intervalValue) {

            MapVo mapVo = new MapVo();
            String section = "";
            Double A = i, B = i + intervalValue;
            if (i + intervalValue >= totalScore) {
                B = totalScore;
                section = A + "-" + B;
            } else {
                section = A + "-" + B;
            }
            //[A,B]分数区间人数
            int amount = studentExamMapper.statisticsMap(A, B, examId);
            mapVo.setSection(section);
            mapVo.setPeopelCount(amount);
            mapVoList.add(count++, mapVo);
        }
        return mapVoList;
    }

    /**
     * 统计分析  客观题分析
     *
     * @param examId
     */
    public List<StudentExamQuestionVo> objectiveProblem(Integer examId) {

        List<StudentExamQuestionVo> result = new ArrayList<>();
        Exam exam = examMapper.selectByPrimaryKey(examId);
        if (exam != null) {
            //判断该考试试卷客观题是否是顺序出题
            ExamPaper examPaper = paperMapper.selectByPrimaryKey(exam.getPaperId());
            //枚举区域
            //  Boolean mark = true;
            if (examPaper.getAreas().size() > 0) {
                for (ExamPaperArea examPaperArea : examPaper.getAreas()) {
                    if (examPaperArea.getExtractingStatus().equals(ExtractingStatusEnum.RANDOM.getValue())) {
                        if (examPaperArea.getRules().size() > 0) {
                            //枚举规则
                            for (ExamPaperAreaRule examPaperAreaRule : examPaperArea.getRules()) {
                                if (examPaperAreaRule.getQuestionType().equals(QuestionTypeEnum.SINGLE.getValue())
                                        || examPaperAreaRule.getQuestionType().equals(QuestionTypeEnum.MULTIPLE.getValue())
                                        || examPaperAreaRule.getQuestionType().equals(QuestionTypeEnum.JUDGE.getValue())
                                        || examPaperAreaRule.getQuestionType().equals(QuestionTypeEnum.GAP.getValue())
                                ) {
                                    //  mark = false;
                                    return result;
                                }
                            }

                        }
                    }
                }
            }
            //考试人数
            ExamStatisticsVo esv = studentExamMapper.statistics(examId);
            List<StudentExam> studentExamIdList = studentExamMapper.selectStudentExambyExamId(examId);
            //获取考试题目
            if (studentExamIdList.size() > 0) {
                result = studentExamQuestionMapper.selectQuestionVoByStudentExamId(studentExamIdList.get(0).getId());
            }
            for (StudentExamQuestionVo studentExamQuestionVo : result) {
                int data = studentExamMapper.correctNumber(examId, studentExamQuestionVo.getQuestionId());

                if (studentExamQuestionVo.getQuestionType().equals(QuestionTypeEnum.SINGLE.getValue()) || studentExamQuestionVo.getQuestionType().equals(QuestionTypeEnum.MULTIPLE.getValue())) {
                    List<Option> optionList = optionMapper.selectByQuestionId(studentExamQuestionVo.getQuestionId());
                    //标准答案
                    String ansb = "";

                    for (Option option : optionList) {
                        if (option.getIfAnswer()) {
                            ansb += option.getContent() + "  ";
                        }
                    }
                    studentExamQuestionVo.setStandardAnswer(ansb);
                }

                if (studentExamQuestionVo.getOptions() != null) {
                    //该题已答题人数
                    int questionCount = studentExamMapper.question(examId, studentExamQuestionVo.getQuestionId());
                    for (ExamQuestionOptionVo ev : studentExamQuestionVo.getOptions()) {

                        int optionCount = studentExamMapper.option(examId, studentExamQuestionVo.getQuestionId(), ev.getId());
                        ev.setOptionAccuracy(Double.valueOf(optionCount) / Double.valueOf(questionCount));

                    }
                }
                //正确率=答对人数/总参考人数
                studentExamQuestionVo.setAccuracy(Double.valueOf(data) / Double.valueOf(esv.getPeopleCount()));
            }
        }
        return result;
    }

    /**
     * 交卷后考试成绩界面展示
     *
     * @param studentExamId
     * @return
     */
    public StudentExamPaperVo examResult(Integer studentExamId) {

        StudentExamPaperVo result = studentExamQuestionService.fetchQuestionsByStudentExamId(studentExamId);

        for (StudentExamAreaVo studentExamAreaVo : result.getAreas()) {

            for (StudentExamQuestionVo studentExamQuestionVo : studentExamAreaVo.getQuestions()) {

                //单选题、多选题
                if (studentExamQuestionVo.getQuestionType().equals(QuestionTypeEnum.SINGLE.getValue()) || studentExamQuestionVo.getQuestionType().equals(QuestionTypeEnum.MULTIPLE.getValue())) {
                    List<Integer> submitAnswers = JSON.parseArray(studentExamQuestionVo.getAnswer(), Integer.class);

                    List<Option> optionList = optionMapper.selectByQuestionId(studentExamQuestionVo.getQuestionId());
                    char emumOption = 'A';
                    //标准答案
                    String ansb = "";
                    //学生答案
                    String anss = "";
                    for (Option option : optionList) {
                        if (option.getIfAnswer()) {
                            ansb += emumOption;
                        }
                        if (submitAnswers != null && submitAnswers.contains(option.getId())) {
                            anss += emumOption;
                        }
                        emumOption = (char) (emumOption + 1);
                    }
                    studentExamQuestionVo.setStandardAnswer(ansb);
                    studentExamQuestionVo.setAnswer(anss);
                }
                //判断题
                else if (studentExamQuestionVo.getQuestionType().equals(QuestionTypeEnum.JUDGE.getValue())) {

                    if (studentExamQuestionVo.getAnswer() != null && !"".equals(studentExamQuestionVo.getAnswer()) && !"[]".equals(studentExamQuestionVo.getAnswer())) {
                        List<Integer> submitAnswers = JSON.parseArray(studentExamQuestionVo.getAnswer(), Integer.class);

                        if (submitAnswers != null) {

                            if (submitAnswers.get(0) == 1) {
                                studentExamQuestionVo.setAnswer("正确");
                            } else {
                                studentExamQuestionVo.setAnswer("错误");
                            }
                        }
                    } else {
                        studentExamQuestionVo.setAnswer(null);
                    }

                    if (studentExamQuestionVo.getJudgmentAnswer() == true) {
                        studentExamQuestionVo.setStandardAnswer("正确");
                    } else {
                        studentExamQuestionVo.setStandardAnswer("错误");
                    }
                }
                //材料题
                else if (studentExamQuestionVo.getQuestionType().equals(QuestionTypeEnum.MATERIALS.getValue())) {

                    List<StudentExamQuestionVo> list = studentExamQuestionVo.getStudentExamQuestionVo();
                    if (list != null && list.size() > 0) {
                        for (StudentExamQuestionVo materialQuestion : list) {
                            //单选题、多选题
                            if (materialQuestion.getQuestionType().equals(QuestionTypeEnum.SINGLE.getValue()) || materialQuestion.getQuestionType().equals(QuestionTypeEnum.MULTIPLE.getValue())) {
                                List<Integer> submitAnswers = JSON.parseArray(studentExamQuestionVo.getAnswer(), Integer.class);

                                List<Option> optionList = optionMapper.selectByQuestionId(materialQuestion.getQuestionId());
                                char emumOption = 'A';
                                //标准答案
                                String ansb = "";
                                //学生答案
                                String anss = "";
                                for (Option option : optionList) {
                                    if (option.getIfAnswer()) {
                                        ansb += emumOption;
                                    }
                                    if (submitAnswers != null && submitAnswers.contains(option.getId())) {
                                        anss += emumOption;
                                    }
                                    emumOption = (char) (emumOption + 1);
                                }
                                materialQuestion.setStandardAnswer(ansb);
                                materialQuestion.setAnswer(anss);
                            }
                            //判断题
                            else if (materialQuestion.getQuestionType().equals(QuestionTypeEnum.JUDGE.getValue())) {
                                List<Integer> submitAnswers = JSON.parseArray(materialQuestion.getAnswer(), Integer.class);
                                if (submitAnswers != null) {

                                    if (submitAnswers.get(0) == 1) {
                                        materialQuestion.setAnswer("正确");
                                    } else {
                                        materialQuestion.setAnswer("错误");
                                    }
                                } else {
                                    studentExamQuestionVo.setAnswer(null);
                                }
                                if (materialQuestion.getJudgmentAnswer() == true) {
                                    materialQuestion.setStandardAnswer("正确");
                                } else {
                                    materialQuestion.setStandardAnswer("错误");
                                }
                            }
                        }
                    }

                }
            }
        }


        StudentExam studentExam = studentExamMapper.selectByPrimaryKey(studentExamId);
        Exam exam = examMapper.selectByPrimaryKey(studentExam.getExamId());

        //成绩展示
        if (ScoreShowEnum.SHOW.getValue().equals(exam.getGradeStatus())) {
//            ExamResultVo examResultVo = queryDetails(studentExamId);

            result.setTotalScore(studentExam.getScore() + studentExam.getSubjectiveScore());
        } else {
            result.setTotalScore(null);
        }
        //题目展示
        if (exam.getQuestionStatus().equals(QuestionShowEnum.SHOW.getValue())) {

        } else if (exam.getQuestionStatus().equals(QuestionShowEnum.SHOWING.getValue())) {
            if (studentExam.getReadOverStatus().equals(ReadOverStatusEnum.NO.getValue())) {
                result.setAreas(null);
            }

        } else {
            result.setAreas(null);

        }
        //答案展示
        if (exam.getAnswerStatus().equals(AnswerShowEnum.SHOW.getValue())) {

        } else if (exam.getAnswerStatus().equals(AnswerShowEnum.SHOWING.getValue())) {
        } else if (exam.getAnswerStatus().equals(AnswerShowEnum.SHOWIED.getValue())) {
            if (studentExam.getReadOverStatus().equals(ReadOverStatusEnum.NO.getValue())) {
                result.setAreas(null);
            }

        } else {
            result.setAreas(null);
        }
        return result;
    }

    public int toLead(MultipartFile file, Integer examId) throws Exception {
//        try {
        List<SubjectiveExcelDto> subjectiveExcelDtoList = new ArrayList<>();

        SubjectiveExcelListener listener = new SubjectiveExcelListener();

        EasyExcel.read(file.getInputStream(), SubjectiveQuestionScoreData.class, listener).sheet().doRead();
        subjectiveExcelDtoList = listener.getStudentDList();


        if (subjectiveExcelDtoList.isEmpty()) {
            //throw new CustomException("导入学员信息为空");
            return -1;
        }
        //上传主观题关联的学生考试id集合
        List<Integer> studentExamIdList = new ArrayList<>();

        //遍历每一道主观题
        for (SubjectiveExcelDto subjectiveExcelDto : subjectiveExcelDtoList) {
            if (subjectiveExcelDto.getIdCard() == null || subjectiveExcelDto.getIdCard() == ""
                    || subjectiveExcelDto.getQuestionName() == null || subjectiveExcelDto.getQuestionName() == ""
                    || subjectiveExcelDto.getSubjectiveScore() == null) {
                return -2;
            }
            //获取studentId
            List<Student> studentlist = studentMapper.selectByParams(null, subjectiveExcelDto.getIdCard(), null, null, null, null);
            if (studentlist != null && studentlist.size() > 0) {
                subjectiveExcelDto.setStudentId(studentlist.get(0).getId());
                subjectiveExcelDto.setExamId(examId);
                //获取StudentExamQuestionId和StudentExamId
                List<StudentExamQuestion> seq = studentExamMapper.selectBySubjectiveExcelDto(subjectiveExcelDto);

                if (seq != null && seq.size() > 0) {
                    if (!studentExamIdList.contains(seq.get(0).getStudentExamId())) {
                        // 将未包含的元素添加进listTemp集合中
                        studentExamIdList.add(seq.get(0).getStudentExamId());
                    }
                    //修改主观题得分
                    StudentExamQuestion studentExamQuestion = new StudentExamQuestion();
                    studentExamQuestion.setId(seq.get(0).getId());
                    studentExamQuestion.setSubjectiveScore(subjectiveExcelDto.getSubjectiveScore());
                    studentExamQuestionMapper.updateByPrimaryKeySelective(studentExamQuestion);
                }
            }

        }
        //上传题目得分修改完成后，统计主观题得分及修改对应学生考试的批阅状态
        for (Integer id : studentExamIdList) {
            Double subjectiveScore = 0d;
            StudentExam studentExam = new StudentExam();
            List<StudentExamQuestion> questions = studentExamQuestionMapper.selectByStudentExamId(id);
            if (questions != null && questions.size() > 0) {
                for (StudentExamQuestion seq : questions) {
                    if (seq.getSubjectiveScore() != null) {
                        subjectiveScore += seq.getSubjectiveScore();

                    }
                }
            }
            studentExam.setId(id);
            studentExam.setReadOverStatus(ReadOverStatusEnum.YES.getValue());
            studentExam.setSubjectiveScore(subjectiveScore);
            studentExamMapper.updateByPrimaryKeySelective(studentExam);
        }

//        } catch (Exception e) {
//            throw new CustomException("批量导入失败");
//        }

        return 1;
    }

    public void issueCertificates() {
        List<SysTeam> sysTeams = teanMapper.selectAll(new SysTeam());
        for (SysTeam sysTeam : sysTeams) {
            if (sysTeam.getReviewTime() != null) {
                List<StudentExamScoreVo> studentExamScoreVos = studentExamMapper.selectByCertificate(sysTeam.getReviewTime());
                for (StudentExamScoreVo studentExamScoreVo : studentExamScoreVos) {
                    ExamCertificate ec = new ExamCertificate();
                    ec.setExId(studentExamScoreVo.getExamId());
                    List<ExamCertificate> examCertificateList = examCertificateMapper.queryAll(ec);
                    for (ExamCertificate examCertificate : examCertificateList) {
                        if (studentExamScoreVo.getTotalScore() >= examCertificate.getOverScore()) {
                            List<StudentExam> studentExams = studentExamMapper.selectTime(studentExamScoreVo.getStudentId(), studentExamScoreVo.getExamId(), studentExamScoreVo.getTotalScore());
                            if (studentExams != null && studentExams.size() > 0) {
                                StudentCertificate studentCertificate = studentCertificateMapper.selectLastByCertificateIdSt(examCertificate.getCfId(), studentExamScoreVo.getStudentId());
                                if (studentCertificate != null) {
                                    if (studentExams.get(0).getUpdateTime().compareTo(studentCertificate.getCreateTime()) > 0) {
                                        StudentCertificate upStudentCertificate = new StudentCertificate();
                                        upStudentCertificate.setId(studentCertificate.getId());
                                        upStudentCertificate.setCreateTime(studentExams.get(0).getUpdateTime());
                                        studentCertificateMapper.updateByPrimaryKeySelective(upStudentCertificate);
                                    }

                                } else {
                                    StudentCertificate record = new StudentCertificate();
                                    record.setCertificateId(examCertificate.getCfId());
                                    record.setStudentId(studentExamScoreVo.getStudentId());
                                    //查询当前证书规则
                                    Certificate certificate = certificateMapper.selectByPrimaryKey(examCertificate.getCfId());
                                    record.setCertificateCode(certificate.getCode());
                                    record.setTeamCode(sysTeam.getTeamCode());
                                    record.setCreateTime(studentExams.get(0).getUpdateTime());
                                    studentCertificateMapper.insert(record);
                                }
                            }

                        }
                    }

                }
            }

        }

        /*List<SysTeam> sysTeams = teanMapper.selectAll(new SysTeam());
        for (SysTeam sysTeam:sysTeams) {
            Certificate record = new Certificate();
            record.setTeamCode(sysTeam.getTeamCode());
            List<Certificate> certificateList = certificateMapper.selectCertificate(record);
            for (Certificate certificate:certificateList) {
                ExamCertificate ec = new ExamCertificate();
                ec.setCfId(certificate.getId());
                List<ExamCertificate> examCertificateList = examCertificateMapper.queryAll(ec);
                studentCertificateMapper.selectByStudentId()
            }
        }*/
    }

    public void invalidCertificates() {
        List<StudentCertificate> studentCertificates = studentCertificateMapper.selectByParams(null, null, null, null, null, null);
        for (StudentCertificate studentCertificate : studentCertificates) {
            if (studentCertificate.getCertificate().getTermOfValidity() != null && !"".equals(studentCertificate.getCertificate().getTermOfValidity())) {
                Integer termOfValidity = Integer.valueOf(studentCertificate.getCertificate().getTermOfValidity());
                if (DateUtils.DateCompare(studentCertificate.getCreateTime(), new Date(), termOfValidity)) {
                    ExamCertificate ec = new ExamCertificate();
                    ec.setCfId(studentCertificate.getCertificateId());
                    List<ExamCertificate> examCertificateList = examCertificateMapper.queryAll(ec);
                    flag:
                    for (ExamCertificate examCertificate : examCertificateList) {
                        CourseCategoryExam queryExam = new CourseCategoryExam();
                        queryExam.setExId(examCertificate.getExId());
                        List<CourseCategoryExam> courseCategoryExams = courseCategoryExamMapper.queryAll(queryExam);
                        for (CourseCategoryExam courseCategoryExam : courseCategoryExams) {

                            if (courseCategoryExam.getClassHours() != null && !"".equals(courseCategoryExam.getClassHours())) {
                                List<Integer> categoryIds = courseService.selectDeepCategoryIds(courseCategoryExam.getCcId());
                                List<CoursePackage> coursePackageList = coursePackageService.selectDeepByParams(null, null, null, categoryIds, null, null, null, null);
                                if (coursePackageList != null) {
                                    //该二级分类下，学员已经购买的课程包集合
                                    List<Integer> ids = coursePackageList.stream().map(e -> e.getId()).collect(Collectors.toList());
                                    if (ids != null && ids.size() > 0) {
                                        List<CoursePackage> purchaseList = coursePackageMapper.selectByStudent(studentCertificate.getStudentId(), ids);
                                        List<Integer> coursePackageIds = purchaseList.stream().map(e -> e.getId()).collect(Collectors.toList());
                                        List<QuizRecordDto> quizRecordDtos = quizRecordMapper.queryAndOrder(studentCertificate.getStudentId(), coursePackageIds);
                                        Integer haveHours = 0;
                                        for (QuizRecordDto quizRecordDto : quizRecordDtos) {
                                            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                            try {
                                                Date currdate = format.parse(quizRecordDto.getPayTime());
                                                Calendar ca = Calendar.getInstance();
                                                ca.setTime(currdate);
                                                if (quizRecordDto.getBuyType() != null && quizRecordDto.getBuyTypeNum() != null) {
                                                    if (quizRecordDto.getBuyType() == 0) {
                                                        ca.add(Calendar.YEAR, quizRecordDto.getBuyTypeNum());
                                                    } else if (quizRecordDto.getBuyType() == 1) {
                                                        ca.add(Calendar.MONTH, quizRecordDto.getBuyTypeNum());
                                                    } else if (quizRecordDto.getBuyType() == 2) {
                                                        ca.add(Calendar.WEEK_OF_YEAR, quizRecordDto.getBuyTypeNum());
                                                    } else if (quizRecordDto.getBuyType() == 3) {
                                                        ca.add(Calendar.DATE, quizRecordDto.getBuyTypeNum());
                                                    }
                                                }
                                                currdate = ca.getTime();
                                                long now = DateUtils.getUct8NowDate().getTime();
                                                if (currdate.getTime() >= now) {
                                                    haveHours += quizRecordDto.getClassHours();
                                                }
                                            } catch (ParseException e) {
                                            }
                                        }
                                        if (haveHours >= Integer.valueOf(courseCategoryExam.getClassHours())) {
                                            StudentCertificate upStudentCertificate = new StudentCertificate();
                                            upStudentCertificate.setId(studentCertificate.getId());
                                            upStudentCertificate.setCreateTime(new Date());
                                            studentCertificateMapper.updateByPrimaryKeySelective(upStudentCertificate);
                                            break flag;
                                        }
                                    }
                                }
                            }


                        }
                    }
                }
            }

        }
    }
}
